﻿using GVmakerForWin;
using Script.Interpreter;
using Script.Interpreter.IO;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using UnityEngine;
using UnityEngine.UI;
using System.Threading;
using Script.Interpreter.Event;

public class StartScript : MonoBehaviour {
    public Form form;
    public VirtualMachine VM;
    public Text text;
    public RawImage image;
    public Texture2D texture2D;
    DefaultKeyModel key;
    ScreenModelImp screen;
    public string appName = "新英雄坛说";
    public List< int> keyValues=new List<int> ();
    public List<char> keyCodes=new List<char> ();
    int[] mBuffer = new int[ScreenModel.WIDTH * ScreenModel.HEIGHT];
    public string RootPath;
    // Use this for initialization
    void Start () {
        //form = new GVmakerForWin.MainForm();
        //((GVmakerForWin.MainForm)form).MainForm_Load(null, null);
        Util.LoadFont();
        texture2D = new Texture2D(ScreenModel.WIDTH, ScreenModel.HEIGHT);
        image.texture = texture2D;
        //key = new DefaultKeyModel(new KeyModelSysInfoImpl(null));
        key = new DefaultKeyModel(new SysInfo());
        keyValues.Add((int)KeyCode.W);
        keyValues.Add((int)KeyCode.S);
        keyValues.Add((int)KeyCode.D);
        keyValues.Add((int)KeyCode.A);
        
        //keyValues.Add((int)KeyCode.Mouse0);
        for (int i = 20; i < 20+ keyValues.Count; i++)
        {
            keyCodes.Add((char)i);
        }
        keyValues.Add((int)KeyCode.H);
        keyCodes.Add((char)28);
        keyValues.Add((int)KeyCode.J);
        keyCodes.Add((char)113);
        keyValues.Add((int)KeyCode.K);
        keyCodes.Add((char)13);
        keyValues.Add((int)KeyCode.L);
        keyCodes.Add((char)27);

        key.setKeyMap(new DefaultKeyMap(keyValues.ToArray (), keyCodes.ToArray ()));
        VM = new VirtualMachine(new GvmConfig(), new DefaultFileModel(new FileS(RootPath)),key );
        VM.loadApp(LavApp.createLavApp(new System.IO.FileStream(RootPath + "/" + appName +".lav", System.IO.FileMode.Open)));
        screen = (ScreenModelImp)VM.screen;
        //InvokeRepeating("Refresh", 0.1f, 0.5f);
        screen.refreshEvent = ()=> { isRefresh = true; };
        thread = new Thread(NextStep);
        thread.Start();
        //VM.nextStep();

    }
    public float currentTime;
    [SerializeField]private bool isRefresh;
    public int H=28;
	// Update is called once per frame
	void Update () {
        if(H!= keyCodes[4])
        {
            keyCodes[4] = (char)H;
            key.SetKeyCodes(keyCodes.ToArray());
        }
		//if(Input .GetKeyDown(KeyCode .R))
  //      {
  //          Refresh();
  //      }
        if (isRefresh)
        {
            Refresh();
        }
        for (int i = 0; i < keyValues.Count; i++)
        {
            KeyCodeEvent(keyValues[i]);
        }
        //VM.nextStep();
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            UnityEngine.Application.LoadLevel(UnityEngine.Application.loadedLevelName);
        }
    }

    public void KeyCodeEvent(int code)
    {
        if(Input .GetKeyDown((KeyCode)code))
        {
            key.keyPreesed(code);
            //VM.nextStep();
            isKeyStep = true;
            //isRefresh = true;
        }
        if (Input.GetKeyUp((KeyCode)code))
        {
            //key.keyPreesed(code);
            key.keyReleased(code);
            //isRefresh = true;
            isKeyStep = false;

        }
    }

    //private void OnGUI()
    //{
    //    KeyCode code = KeyCode.None;
    //    if (Input.anyKeyDown)
    //    {
    //        code =Event.current.keyCode;
            
    //        isRefresh =true;
    //    }
    //    if(code!=KeyCode.None)
    //    {
    //        if(Input.GetKeyDown(code))
    //        {
    //            key.keyPreesed((int)code);
    //        }
    //        if (Input.GetKeyUp(code))
    //        {
    //            key.keyReleased((int)code);
    //        }
    //    }

       
    //}
    Thread thread;
    public bool isExit;
    public bool isKeyStep;

    public void NextStep()
    {
        while(!isExit)
        {
            //if(isKeyStep)
            //  Thread.Sleep(100);
            VM.nextStep();
        }
    }

    private void OnApplicationQuit()
    {
        isExit = true;
        key.isExit = true;

    }

    private void OnDestroy()
    {
        isExit = true;
        key.isExit = true;
    }
    Area area = new Area(0,0, ScreenModel.WIDTH, ScreenModel.HEIGHT);
    public Color blackColor;
    public Color whiteColor;
    public void Refresh()
    {
        isRefresh = false;
        if (screen.currData == null) return;
        int[] buffer= screen.getRGB(mBuffer, area, 1, 0);
        for (int y = ScreenModel.HEIGHT-1; y >0 ; y--)
        {
            for (int x = 0; x < ScreenModel.WIDTH; x++)
            {
                texture2D.SetPixel(x, y, buffer[y * ScreenModel.WIDTH + x] > 0 ? whiteColor : blackColor); ;
            }
        }
        texture2D.Apply();
    }
}
